<template>
  <!-- 建设验收审核 -->
  <div>
    <!-- 搜索 -->
    <TopFilter
      ref="commonTopFilter"
      :list="topFilterInit"
      :cols="3"
      labelWidth="100"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    />
    <!-- 经销商弹窗 -->
    <BaseDialog
      title="经销商查询"
      :visible.sync="visibleDealer"
      width="1000px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <!-- <dealer-madal ref="addDialog" @close="closeDealer" /> -->
      <dealer-madal  ref='addDialog' selectType='multiple' v-model="initDealerData"  @close="closeDealer" />
    </BaseDialog>
  </div>
</template>

<script>
  import dealerMadal from '@/pages/cms-common/dealerdata'
  import { dictionary } from '@/utils/dictMixin';
  import { region } from '@/api/cms-common/region';//行政区域
  import { getRegion, getCommunity,getLevelOneArea, getLevelTwoAndThreeArea } from '@/api/cms-common/dealerdata/index';//事业部，办事处
  import { dealerCommon, DICT_CODE } from '@/api/cms-api/origin/commonDealerType';		//经销商类型工具类
  import {getModelAll} from '@/api/cms-common/basedata';
  export default {
    mixins: [dictionary,region,dealerCommon],
    components: {
      dealerMadal
    },
    props:{
    },
    data() {
      return {
        visibleDealer: false,
        initDealerData:{},  //经销商弹窗参数
        dealerIds:[],
        topFilterInit: this.topFilterInitFun(),
        ORG_TYPE_SERVICE_WAR_AREA:15061019, //服务战区
        ORG_TYPE_SERVICE_BIG_AREA:15061020, //服务大区
        ORG_TYPE_SERVICE_SMALL_AREA:15061021, //服务小区
      };
    },
    mounted(){
      this.initProvince();
      this.getTopLevelArea(this.ORG_TYPE_SERVICE_WAR_AREA,'serviceWarArea');
    },
    methods: {
      transformStatus(val){
        if(!Array.isArray(val)){
          let status = parseInt(val);
          if(isNaN(status)){
            return null;
          }else{
            return status;
          }
        }else{
          return val;
        }
      },
      //初始化所在省份
      async initProvince(){
        let pl = await this.createRegionList();
        this.topFilterInit.find(item => item.fieldName === 'provinceId').itemList = pl;
      },
      //初始化所在市数据
      async initCity(provinceId){
        if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
          return;
        }
        //取省数据
        let rd = this.getRegionData();
        this.cityData = rd[provinceId].children;
        let cl = this.createSubRegionList(this.cityData);
        //初始化市，清除原值
        let city = this.topFilterInit.find(item => item.fieldName === 'cityId');
        city.itemList = cl;
        city.initialValue = '';
        //清除区县
        let district = this.topFilterInit.find(item => item.fieldName === 'districtId');
        district.itemList = [];
        district.initialValue = '';
      },
      //初始化所在县市数据
      async initTown(cityId){
        if(!cityId || cityId==null || typeof(cityId)=='undefined'){
          return;
        }
        let td = this.cityData[cityId].children;
        let tl = this.createSubRegionList(td);
        //初始化区县，清除原值
        let district = this.topFilterInit.find(item => item.fieldName === 'districtId');
        district.itemList = tl;
        district.initialValue = '';
      },
      //获取大区
      async getBigArea() {
        const res = await getRegion();
        if (res.resultCode === 200) {
          this.topFilterInit.find(item => item.fieldName === 'serviceBigArea').itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
        }
      },
      //搜索获取数据
      changeHandle(val) {

        this.multiSelectJoin(val,['serviceShopType','dealerStatus','modelName']);

        this.$emit('filterChange', val)
      },

      //日期转换
      resolveSearchTime(obj, keys) {
        keys.forEach(key => {
          const item = obj[key];
          if (item) {
            obj[`${key}From`] = item[0];
            obj[`${key}To`] = item[1];
          } else {
            obj[`${key}From`] = "";
            obj[`${key}To`] = "";
          }
        });
      },
      //多项选择格式化
      multiSelectJoin(obj, keys) {
        keys.forEach(key => {
          const data = obj[key];
          if (Array.isArray(data)) {
            obj[`${key}Str`] = data.join(",");
          }else {
            obj[`${key}Str`] = null;
          }
        });
      },
      collapseHandle() {
        this.$emit('onCollapse', this.selectRow)
      },
      // 经销商打开窗口 -传数据
      dealerHandle() {
        this.initDealerData={
          excludeBigCustomer:false,//是否查询大客户经销商，如果查询 true，不查询 false
        }
        this.visibleDealer = true;
      },
      // 经销商关闭窗口 -返回数据
      closeDealer(data) {
        let dealerCodes = [];
        let dealerNames = [];
        if(data && data.data && data.data.length > 0){
          for(let i in data.data){
            dealerCodes.push(data.data[i].dealerCode);
            dealerNames.push(data.data[i].dealerName);
          }
        }

        this.topFilterInit.find(item => item.fieldName === 'dealerNames').initialValue = dealerNames.join(",");
        this.dealerCodes = dealerCodes;
        this.visibleDealer = data.visible; //关闭弹窗
      },
      //搜索数据
      topFilterInitFun() {
        return [
          { type: 'INPUT', label: '公司代码', fieldName: 'dealerCompanyCode', initialValue: ''},
          { type: 'INPUT', label: '服务中心代码', fieldName: 'dealerCode', initialValue: ''},
          { type: 'INPUT', label: '服务中心名称',fieldName : 'dealerName', placeholder: '请输入', initialValue: ''},
          { type: 'INPUT', label: '服务中心简称',fieldName : 'dealerShortname', placeholder: '请输入', initialValue: ''},
          { type: 'SELECT', label: '服务战区', fieldName: 'serviceWarArea', placeholder: '请选择', initialValue: ''
            ,itemList: [],
            change: val => {
              this.changeTopAndMiddleLevelArea(val,this.ORG_TYPE_SERVICE_BIG_AREA,
                'serviceWarArea','serviceBigArea','serviceSmallArea');
            },
            },
          { type: 'SELECT', label: '服务大区', fieldName: 'serviceBigArea', placeholder: '请选择', initialValue: ''
            ,itemList: [],
            change: val => {
              this.changeTopAndMiddleLevelArea(val,this.ORG_TYPE_SERVICE_SMALL_AREA,
                'serviceBigArea','serviceSmallArea','serviceSmallArea');
            },
          },
          { type: 'SELECT', label: '服务小区', fieldName: 'serviceSmallArea', placeholder: '请选择', initialValue: ''
            ,itemList: [],
          //   change: val => {
          //     this.changeTopAndMiddleLevelArea(val,this.ORG_TYPE_SERVICE_SMALL_AREA,
          //       'serviceSmallArea','serviceSmallArea','serviceSmallArea');
          // },
          },
          // { type: 'SELECT', label: '省份', fieldName: 'provinceId', placeholder: '请选择', initialValue: '', itemList: [],change: props => this.initCity(props)},
          // { type: 'SELECT', label: '城市', fieldName: 'cityId', placeholder: '请选择', initialValue: '', itemList: [], change: props => this.initTown(props)},
          // { type: 'SELECT', label: '县区', fieldName: 'districtId', placeholder: '请选择', initialValue: '', itemList: [] },
          // { type: 'MULTIPLE_SELECT', label: '服务中心类型', fieldName: 'serviceShopType', placeholder: '请选择', initialValue: '', itemList: this.createDictList('1621') },
          { type: 'MULTIPLE_SELECT', label: '经营状态', fieldName: 'dealerStatus', placeholder: '请选择', initialValue: '', itemList: this.createDictList('1724') },
          { type: 'MULTIPLE_SELECT', label: '授权车型', fieldName: 'modelName', placeholder: '请选择', initialValue: '', itemList: this.getModel() }
          // { type: 'SELECT', label: '网点类型', fieldName: 'branchType', placeholder: '请选择',  initialValue: '', itemList: this.createDictList('1623') },
        ];
      },
      //获取所有车型
      async getModel() {
        let res = await getModelAll();
        if (res.resultCode === 200) {
          this.topFilterInit.find(item => item.fieldName === 'modelName').itemList = res.data.map(x => ({text:x.modelName,value:x.modelId}));

        }
      },
      //获取顶层组织数据
      async getTopLevelArea(areaType, filedName) {
        const res = await getLevelOneArea(areaType);
        if (res.resultCode === 200) {
          this.topFilterInit.find(item => item.fieldName === filedName).itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
        }
      },

      //顶层和中层组织数据修改
      async changeTopAndMiddleLevelArea(deptId, sonAreaType, parentFieldName, sonFieldName,smallFieldName, flag = true) {
        let sonArea = this.topFilterInit.find(item => item.fieldName === sonFieldName);
        let smallArea = this.topFilterInit.find(item => item.fieldName === smallFieldName);
        if (!deptId) {
          sonArea.initialValue = '';
          sonArea.itemList = [];
          smallArea.initialValue = '';
          smallArea.itemList = [];
        } else {
          if (flag) {
            //正常的级联，清空原来选择的数据
            sonArea.initialValue = '';
            smallArea.initialValue = '';
          }
          const res = await getLevelTwoAndThreeArea(sonAreaType, deptId);
          if (res.resultCode === 200) {
            sonArea.itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
          }
        }
      },

    },
  };
</script>

<style lang="less" scoped>
</style>
